package mahan.test.data.mongodb;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;

import java.util.Date;
import java.util.Map;

import mahan.data.model.Order;
import mahan.data.mongodb.MahanDB;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;

public class OrderTestCase {
	private MahanDB mahanDb;

	@After
	public void clean() {
		mahanDb.get().dropDatabase();
	}

	@Before
	public void setup() {
		mahanDb = new MahanDB("localhost", 27017, "orderdb");
		DB db = mahanDb.get();
		assertNotNull(db);
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Test
	public void testOrder() throws Exception {
		clean();
		Date date = new Date();
		Order order = new Order(1, 2, date);
		order.setCountryTax(1.0);
		order.setCountyTax(0.2);
		order.setDiscount(0.3);
		order.setFulfilledOn(date);
		order.setShippingAddress("23 c");
		order.setShippingCity("z");
		order.setShippingCost(33.1);
		order.setShippingCountry("zx");
		order.setShippingEmail("a@aa");
		order.setShippingPhone("111");
		order.setShippingState("ss");
		order.setShippingZip("11111");
		order.setStateTax(0.5);
		order.setStatus("done");
		order.setTotalCost(233.1);

		// Store into DB
		BasicDBObject dbo = new BasicDBObject();
		dbo.putAll(order.get());
		DBCollection coll = mahanDb.createCollection("order");
		coll.save(dbo);

		// Retrieve from DB
		DBObject fromDB = coll.findOne();
		Map dbMap = fromDB.toMap();
		Integer id = (Integer) dbMap.get("id");
		Integer custID = (Integer) dbMap.get("cid");
		Order from = new Order(id.intValue(), custID.intValue(),
				(Date) dbMap.get("enter"));
		from.put(fromDB.toMap());

		assertEquals("23 c", from.getShippingAddress());
		assertEquals("z", from.getShippingCity());
		assertEquals("zx", from.getShippingCountry());
		assertEquals("ss", from.getShippingState());
		assertEquals("111", from.getShippingPhone());
		assertEquals("a@aa", from.getShippingEmail());
		assertEquals(33.1, from.getShippingCost(), 0.01);
		assertEquals(1.0, from.getCountryTax(), 0.01);
		assertEquals(0.2, from.getCountyTax(), 0.01);
		assertEquals(0.3, from.getDiscount(), 0.01);
		assertEquals(1, from.getId());
		assertEquals(2, from.getCustomerID());
		assertEquals(date, from.getEnteredOn());
		assertEquals(date, from.getFulfilledOn());
		assertEquals(33.1, from.getShippingCost(), 0.01);
		assertEquals(0.5, from.getStateTax(), 0.01);
		assertEquals("done", from.getStatus());
		assertEquals(233.1, from.getTotalCost(), 0.01);
	}
}